package com.xingfly.order.service;

import com.xingfly.order.model.Order;
import com.xingfly.order.model.OrderId;
import com.xingfly.order.repository.OrderRepository;
import com.xingfly.order.sdk.command.ChangeOrderAddressCommand;
import com.xingfly.order.sdk.command.ChangeProductCountCommand;
import com.xingfly.order.sdk.command.CreateOrderCommand;
import com.xingfly.order.sdk.representation.OrderRepresentation;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * Created by SuperS on 2019/11/15.
 *
 * @author SuperS
 */
@Service
public class OrderAppService {

    @Resource
    private OrderRepository orderRepository;


    @Transactional(rollbackFor = Exception.class)
    public OrderId create(CreateOrderCommand command) {
        Order order = Order.create(command);
        orderRepository.save(order);
        return order.getId();
    }

    @Transactional(rollbackFor = Exception.class)
    public OrderId changeOrderAddress(String id, ChangeOrderAddressCommand command) {
        Order order = orderRepository.findById(OrderId.from(id))
                .orElseThrow(() -> new RuntimeException("Order Not Found!"));
        order.changeAddress(command.getAddress());
        orderRepository.save(order);
        return order.getId();
    }

    @Transactional(rollbackFor = Exception.class)
    public Boolean changeProductCount(String id, ChangeProductCountCommand command) {
        Order order = orderRepository.findById(OrderId.from(id))
                .orElseThrow(() -> new RuntimeException("Order Not Found!"));
        order.changeProductCount(command.getProductId(), command.getCount());
        orderRepository.save(order);
        return true;
    }

    public OrderRepresentation findById(String id) {
        Order order = orderRepository.findById(OrderId.from(id))
                .orElseThrow(() -> new RuntimeException("Order Not Found!"));
        return order.toRepresentation();
    }
}
